package com.cross.xml;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.cross.core.AbstractReader;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.core.Item;
import com.cross.core.Row;

public class SimpleXmlReader extends AbstractReader {

	private File file;
	private SAXReader reader = new SAXReader();
	private Document document = null;
	Element root = null;
	Iterator<Element> iterator = null;

	public SimpleXmlReader(File file) throws DocumentException {
		this.file = file;
		init();
	}

	private void init() throws DocumentException {
		document = reader.read(file);
		root = document.getRootElement(); // Get the root node of XML
		iterator = root.elementIterator();
		header = createHeader(root);
	}

	@Override
	protected boolean nextRow() {
		return nextRowImpl();
	}

	private boolean nextRowImpl() {
		if(!iterator.hasNext()){
			return false;
		}
		currentRow = toRow(iterator.next());
		return null != currentRow;
	}

	public Header createHeader(Element root) {
		Header header = new Header();
		List rootList = root.elements();
		if (rootList.size() <= 0) {
			return null;
		}
		Element element = (Element) rootList.get(0);
		List<Element> headerElementList = element.elements();
		Element e;
		for(int i=0; i<headerElementList.size(); i++){
			e = headerElementList.get(i);
			header.add(new Column(i, e.getName(), e.elementTextTrim("type")));
		}
		return header;
	}

	private Row toRow(Element e) {
		Row row = new Row();
		Iterator<Element> iterator = e.elementIterator();
		while (iterator.hasNext()) {
			row.append(toItem(iterator.next()));
		}
		return row;
	}

	private Item toItem(Element e) {
		Item item = new Item(e.getData(), e.attributeValue("type"));
		return item;
	}

	@Override
	public void close() {

	}
}
